package com.dfch.auto.appium.main;

import com.dfch.auto.appium.app.AutoAndroidDouYin;
import com.dfch.auto.appium.app.AutoApp;
import com.dfch.auto.appium.bean.AutoBean;
import com.dfch.auto.appium.bean.AutoParamBean;
import com.dfch.auto.appium.pool.AutoThreadPool;
import com.dfch.auto.appium.utils.FastJsonUtils;
import io.appium.java_client.MobileBy;
import io.appium.java_client.MobileElement;
import io.appium.java_client.TouchAction;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.android.AndroidKeyCode;
import io.appium.java_client.remote.AndroidMobileCapabilityType;
import io.appium.java_client.remote.AutomationName;
import io.appium.java_client.remote.MobileCapabilityType;
import io.appium.java_client.touch.WaitOptions;
import io.appium.java_client.touch.offset.PointOption;
import org.openqa.selenium.Platform;
import org.openqa.selenium.remote.DesiredCapabilities;

import java.net.URL;
import java.time.Duration;
import java.util.List;

/**
 * @author ldcmaxim on 04/04/2018.
 */
public class AutoScriptCopy {
    //private static final Logger LOGGER = LoggerFactory.getLogger(AutoScriptMain.class);

    public static void main(String[] args) throws Exception {
        if (args == null || args.length <= 0) {
            return;
        }
        String str = "{\"action\":[{\"platformVersion\":\"7.0\",\"deviceName\":\"36a98632\",\"appPackage\":\"com.ss.android.ugc.aweme\",\"appActivity\":\"com.ss.android.ugc.aweme.splash.SplashActivity\",\"remote\":\"http://127.0.0.1:6000/wd/hub\", \"comment\":\"这首歌叫什么?\"}]}";
        System.out.println(args[0]);
        AutoBean base = FastJsonUtils.getObject(args[0], AutoBean.class);
        if (base == null || base.action == null || base.action.isEmpty()) {
            return;
        }

        //LOGGER.info("all params:{}", args[0]);

        List<AutoParamBean> params = FastJsonUtils.getListObjects(base.action, AutoParamBean.class);
        if (params.isEmpty()) {
            return;
        }

        for (AutoParamBean param : params) {
            StartDouYin(param);
        }
    }

    private static void StartDouYin(AutoParamBean bean) {
        AutoThreadPool.getInstance().executeAsyncTask(new Runnable() {
            @Override
            public void run() {
                AutoApp app = new AutoAndroidDouYin();
                app.init(bean.deviceName, bean.platformVersion, bean.url);
                app.execute(bean.comment, 5);
                app.release();
            }
        });
    }

    private static void StartDouYin3(AutoParamBean bean) {
        AutoThreadPool.getInstance().executeAsyncTask(new Runnable() {
            @Override
            public void run() {
                AndroidDriver<AndroidElement> driver = null;
                try {
                    DesiredCapabilities capabilities = new DesiredCapabilities();
                    // Platform
                    capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, Platform.ANDROID);
                    // Android system version
                    capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, bean.platformVersion);
                    // Adb device name
                    capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, bean.deviceName);
                    // Reset app and clear cache
                    capabilities.setCapability(MobileCapabilityType.NO_RESET, true);
                    // Application package name
                    capabilities.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, "com.ss.android.ugc.aweme");
                    // Application activity name
                    capabilities.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, "com.ss.android.ugc.aweme.splash.SplashActivity");
                    // Unicode keyboard
                    capabilities.setCapability(AndroidMobileCapabilityType.UNICODE_KEYBOARD, true);
                    // Hide keyboard
                    capabilities.setCapability(AndroidMobileCapabilityType.RESET_KEYBOARD, true);
                    // Set automation type
                    capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.APPIUM);


                    driver = new AndroidDriver<>(new URL(bean.url), capabilities);
                    while (true) {
                        // 等待视频加载
                        Thread.sleep(3000);

                        try {
                            // 点击评论按钮
                            MobileElement showComment = driver.findElement(MobileBy.id("com.ss.android.ugc.aweme:id/lq"));
                            showComment.click();
                            Thread.sleep(200);
                        } catch (Exception e) {
                            continue;
                        }

                        try {
                            // 点击评论输入框
                            MobileElement showCommentInput = driver.findElement(MobileBy.id("com.ss.android.ugc.aweme:id/lr"));
                            showCommentInput.click();
                            showCommentInput.sendKeys(bean.comment);
                            Thread.sleep(500);
                        } catch (Exception e) {
                            // 返回主页
                            driver.pressKeyCode(AndroidKeyCode.KEYCODE_BACK);
                            continue;
                        }

                        try {
                            // 获取发送按钮
                            MobileElement send = driver.findElement(MobileBy.id("com.ss.android.ugc.aweme:id/lt"));
                            send.click();
                            Thread.sleep(2000);
                        } catch (Exception e) {
                            // 两次返回主页
                            driver.pressKeyCode(AndroidKeyCode.KEYCODE_BACK);
                            Thread.sleep(200);
                            driver.pressKeyCode(AndroidKeyCode.KEYCODE_BACK);
                            continue;
                        }

                        // 返回主页
                        driver.pressKeyCode(AndroidKeyCode.KEYCODE_BACK);

                        Thread.sleep(200);

                        // 切换下一个视频
                        SwipeUp(driver);
                    }
                } catch (Exception e) {
                    // Disconnect to server driver
                    if (driver != null) {
                        driver.quit();
                    }
                }
            }
        });
    }


    private static void StartDouYin2(AutoParamBean bean) {
        AutoThreadPool.getInstance().executeAsyncTask(new Runnable() {
            @Override
            public void run() {
                AndroidDriver<AndroidElement> driver = null;
                try {
                    DesiredCapabilities capabilities = new DesiredCapabilities();
                    // Platform
                    capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, Platform.ANDROID);
                    // Android system version
                    //capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "7.0");
                    capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, bean.platformVersion);
                    // Adb device name
                    // capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "36a98632");
                    capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, bean.deviceName);
                    // Reset app and clear cache
                    capabilities.setCapability(MobileCapabilityType.NO_RESET, true);
                    // Application package name
                    capabilities.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, "com.ss.android.ugc.aweme");
                    // Application activity name
                    capabilities.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, "com.ss.android.ugc.aweme.splash.SplashActivity");
                    // Unicode keyboard
                    capabilities.setCapability(AndroidMobileCapabilityType.UNICODE_KEYBOARD, true);
                    // Hide keyboard
                    capabilities.setCapability(AndroidMobileCapabilityType.RESET_KEYBOARD, true);
                    // Set automation type
                    capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.APPIUM);


                    driver = new AndroidDriver<>(new URL(bean.url), capabilities);
                    while (true) {
                        // 等待视频加载
                        Thread.sleep(3000);

                        // 点击评论按钮
                        //new TouchAction(driver).tap(PointOption.point(608, 694)).perform();
                        new TouchAction(driver).tap(PointOption.point(1283, 1688)).perform();

                        Thread.sleep(200);

                        // 点击评论输入框
                        TouchAction input = new TouchAction(driver);
                        input.tap(PointOption.point(746, 2474)).perform();
                        //input.tap(PointOption.point(328, 934)).perform();

                        try {
                            // 获取发送按钮
                            MobileElement send = driver.findElement(MobileBy.id("com.ss.android.ugc.aweme:id/lt"));
                            send.sendKeys(bean.comment);
                            send.click();
                        } catch (Exception e) {
                            // 返回主页
                            driver.pressKeyCode(AndroidKeyCode.KEYCODE_BACK);
                            continue;
                        }
                        // 等待发送完成
                        Thread.sleep(2000);

                        // 返回主页
                        driver.pressKeyCode(AndroidKeyCode.KEYCODE_BACK);

                        Thread.sleep(200);

                        // 切换下一个视频
                        SwipeUp(driver);
                    }
                } catch (Exception e) {
                    // Disconnect to server driver
                    if (driver != null) {
                        driver.quit();
                    }
                }
            }
        });
    }

    private static void SwipeDown(AndroidDriver driver) {
        int width = driver.manage().window().getSize().width;
        int height = driver.manage().window().getSize().height;
        TouchAction action = new TouchAction(driver);
        action.press(PointOption.point(width / 2, height / 2));
        action.waitAction(WaitOptions.waitOptions(Duration.ofMillis(200)));
        action.moveTo(PointOption.point(width / 2, height * 3 / 4));
        action.release();
        action.perform();
    }


    private static void SwipeUp(AndroidDriver driver) {
        int width = driver.manage().window().getSize().width;
        int height = driver.manage().window().getSize().height;
        TouchAction action = new TouchAction(driver);
        action.press(PointOption.point(width / 2, height / 2));
        action.waitAction(WaitOptions.waitOptions(Duration.ofMillis(200)));
        action.moveTo(PointOption.point(width / 2, height / 4));
        action.release();
        action.perform();
    }

}
